/*
Copyright (C) 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// ---------------------- Default Parsers ------------------------

// Generates sequential IDs.
//
// Some feeds do not provide entry IDs, however the gadget needs each entry
// to have a unique ID. When parsing a feed and encountering an ID-less entry,
// use this to create an ID.
var IdGenerator = new function() {
  this.nextId = 0;

  this.getNextId = function() {
    return ++this.nextId;
  };
};

function stripHtml(s) {
  s = s.replace(/(<([^>]*)>)/ig, '');

  return s;
}

// Generic RSS 2.0 parser.
// Returns array of data objects.
function parseRSS20(doc, maxEntries) {
  debug.trace('Parsing RSS 2.0 feed.');
  var entries = [];

  try {
    var entryElements = doc.getElementsByTagName('item');

    for (var i = 0; i < entryElements.length && i < maxEntries; ++i) {
      var entry = entryElements[i];
      var entryData = {};

      // ID.
      if (entry.getElementsByTagName('guid').length > 0) {
        entryData['id'] = entry.getElementsByTagName('guid')[0].text;
      } else {
        entryData['id'] = IdGenerator.getNextId();
      }

      // Entry title.
      entryData['title'] = entry.getElementsByTagName('title')[0].text;

      // Strip any possible HTML from title.
      entryData['title'] = stripHtml(entryData['title']);

      // Publish date.
      if (entry.getElementsByTagName('pubDate').length > 0) {
        var pubDate = entry.getElementsByTagName('pubDate')[0].text;
        entryData['published'] = new Date(pubDate);
      }

      // Entry content.
      entryData['content'] = entry.getElementsByTagName('description')[0].text;

      // Link.
      entryData['link'] = entry.getElementsByTagName('link')[0].text;

      entries.push(entryData);
    }
  } catch(e) {
    debug.error('Error parsing RSS 2.0 feed: ' + e.message);
    return;
 }

  debug.trace('Successfully parsed ' + entries.length + ' entries.');

  return entries;
}
